package com.gavindon.android.network

import com.gavindon.android.base.SP_TOKEN
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.utils.SpUtils
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response


/**
 * description:
 * Created by liNan on  2021/5/6 16:27
 */
class RequestInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()
        val urlBuilder = request.url.newBuilder()
//        builder.addHeader("X-TOKEN", SpUtils.get(SP_TOKEN, ""))
        builder.addHeader("X-TOKEN", LoginStatus.token)
        if (request.method == "GET") {
            urlBuilder.addEncodedQueryParameter("deviceType", "tv_android")
            val httpUrl = urlBuilder.build()
            builder.url(httpUrl)
        } else {
            val bodyBuilder: FormBody.Builder = FormBody.Builder()
            if (request.body is FormBody) {
                val formBody = request.body as FormBody
                for (i in 0 until formBody.size) {
                    bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
                }
            }
            // 这里可以添加一些公共post参数
            bodyBuilder.addEncoded("deviceType", "tv_android")
            val newBody = bodyBuilder.build()
            builder.post(newBody)
        }
        return chain.proceed(builder.build())
    }
}